<?php

namespace App\Handlers;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Constraint;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Intervention\Image\Facades\Image;

class ImageUploadHandler
{
    protected $allowedExt = ['png', 'jpg', 'gif', 'jpeg'];

    /**
     * @param UploadedFile $file
     * @param string $folder
     * @param string $filePrefix
     * @param bool $maxWidth
     * @return array
     * @throws \Exception
     */
    public function save($file, $folder, $filePrefix, $maxWidth = false)
    {
        $extension = strtolower($file->getClientOriginalExtension()) ? : 'png';
        $filename = $filePrefix . '_' . time() . '_' . Str::random(10) . '.' .$extension;
        $filename = '/uploads/images/' . $folder . '/' . date('Ym/d', time()) . '/' . $filename;

        if (! in_array($extension, $this->allowedExt)) {
            throw new \Exception('图片格式有误！');
        }
//        if ($maxWidth && $extension != 'gif') {
//            $this->reduceSize($file->getRealPath(), $maxWidth);
//        }

        $response = Storage::disk(config('admin.upload.disk'))->put($filename, fopen($file, 'r'));
        if (!$response) {
            throw new \Exception('上传图片失败！');
        }

        $path = 'http://' . env('QINIU_DOMAIN') . $filename;

        return [
            'path' => $path,
        ];
    }

    public function reduceSize($filePath, $maxWidth)
    {
        $image = Image::make($filePath);

        $image->resize($maxWidth, null, function (Constraint $constraint) {
            // 设定宽度是 $max_width，高度等比例双方缩放
            $constraint->aspectRatio();

            // 防止裁图时，图片尺寸过大
            $constraint->upsize();
        });

        $image->save();
    }
}
